<?php
declare (strict_types = 1);

namespace app\tools;

use app\exception\LogicException;
use Exception;
use OSS\Core\OssException;
use OSS\OssClient;
use think\facade\Log;

final class OssTool
{
    private $bucket;
    private $endpoint;
    private $accessKeyID;
    private $accessKeySecret;

    private $client;

    /**
     * constructor.
     * @throws Exception
     */
    public function __construct()
    {
        $this->bucket = config('oss.bucket');
        $this->endpoint = config('oss.endpoint'); // 上传url
        $this->accessKeyID = config('oss.access_key_id');
        $this->accessKeySecret = config('oss.access_key_secret');

        try {
            $this->client = new OssClient($this->accessKeyID, $this->accessKeySecret, $this->endpoint);
        } catch (OssException $e) {
            throw new LogicException($e->getMessage());
        }

        // Log::debug('oss请求debug:app_secret: {app_secret}, app_id: {app_id}, access_token: {access_token}', [
        //     'app_id' => $this->appID,
        //     'app_secret' => $this->secret,
        //     'access_token' => $this->access_token,
        // ]);
    }

    /**
     * 简单上传--文件上传
     *
     * @param $object
     * @param $filePath
     * @return mixed
     * @throws LogicException
     */
    public function uploadFile($object, $filePath)
    {
        try {
            $this->client->uploadFile($this->bucket, $object, $filePath);
        } catch (OssException $e) {
            throw new LogicException($e->getMessage());
        }

        return $object;
    }

    /**
     * 删除单个文件
     *
     * @param $object
     * @return bool
     * @throws LogicException
     */
    public function deleteObject($object)
    {
        try {
            $this->client->deleteObject($this->bucket, $object);
        } catch (OssException $e) {
            throw new LogicException($e->getMessage());
        }

        return true;
    }

    /**
     * 下载
     *
     * @param $object
     * @param array $options
     * @return string
     * @throws LogicException
     */
    public function getObject($object, $options = [])
    {
        try {
            if (empty($options)) {
                $content = $this->client->getObject($this->bucket, $object);
            } else {
                $content = $this->client->getObject($this->bucket, $object, $options);
            }
            return $content;
        } catch (OssException $e) {
            throw new LogicException($e->getMessage());
        }
    }
}
